<template>
  <view class="viewport theme-light">
    <uv-navbar title="" placeholder bgColor="transparent" leftIcon="" :autoBack="false">
      <template #left>
        控制中心
      </template>
    </uv-navbar>

    <view class="user_content">
      <uv-avatar :src="profile.avatar"></uv-avatar>
      <view class="ml-2 user_detail_content" v-if="memberStore.profile">
        <view class="flex align-center user_detail_login_content">
          <view class="user_detail_login_title"><uv-text :text="profile.name" :lines="1" bold></uv-text></view>
          <view class="user_detail_login_id">
            {{ profile.levelName }}
          </view>
        </view>
        <view class="user_detail_login_id">{{ profile.phone }}</view>
      </view>
      <view v-else class="user_detail_content">
        <view class="user_detail_login_content">
          <view class="user_detail_login_title"><uv-text text="未登录" :lines="1" bold></uv-text></view>
          <view class="user_detail_login_id">ID：</view>
        </view>
        <view class="user_detail_login_btn" @tap="to('', true)">
          立即登录
        </view>
      </view>
    </view>

    <!-- actions -->
    <view class="action_content">
      <!-- actions_title -->
      <view class="action_title"> 常用功能 </view>

      <!-- actions_list -->
      <view class="action_list_content" v-for="(item, index) in actionsListView" :key="index">
        <view class="action_list_icon_content">
          <image class="action_list_icon" :src="item.icon"></image>
        </view>
        <view class="action_list_detail_content">
          <view class="action_list_detail_content_text">
            <view class="action_list_detail_name"> {{ item.action_name }} </view>
            <view class="action_list_detail_dec"> {{ item.action_dec }} </view>
          </view>
          <!-- <switch class="action_switch" :checked="item.action_statu" @change="handleSwitchChange($event, item)" /> -->
          <uv-switch v-model="item.action_statu" asyncChange :loading="item.loading"
            @change="handleSwitchChange($event, item)"></uv-switch>
        </view>
      </view>
    </view>

    <!-- action_module -->
    <view class="module_content">
      <view class="module_title"> 功能模块 </view>
      <scroll-view class="scroll-view" scroll-x="true">
        <view class="module_item">
          <view class="module_item_detail" v-for="(item, index) in actionModulesListView" :key="index">
            <text class="">
              {{ item.action_name }}
            </text>
          </view>
        </view>
      </scroll-view>
    </view>


    <!-- <view class="bg-white menu mt-3">
      <uv-cell-group>
        <uv-cell icon="setting-fill" title="使用帮助" isLink size="large" :border="false" :cellStyle="cellStyle"
          :clickable="false" @click="tips">
          <template #icon>
            <uv-image src="/static/images/my/help.png" height="24" width="24"></uv-image>
          </template>
        </uv-cell>
        <uv-cell icon="integral-fill" title="修改密码" isLink size="large" :border="false" :cellStyle="cellStyle"
          :clickable="false" @click="tips">
          <template #icon>
            <uv-image src="/static/images/my/password.png" height="24" width="24"></uv-image>
          </template>
        </uv-cell>
        <uv-cell icon="integral-fill" title="意见反馈" isLink size="large" :border="false" :cellStyle="cellStyle"
          :clickable="false" @click="tips">
          <template #icon>
            <uv-image src="/static/images/my/feedback.png" height="24" width="24"></uv-image>
          </template>
        </uv-cell>
        <uv-cell icon="integral-fill" title="版本号" isLink size="large" :border="false" :cellStyle="cellStyle"
          :clickable="false" value="1.0.1">
          <template #icon>
            <uv-image src="/static/images/my/version.png" height="24" width="24"></uv-image>
          </template>
        </uv-cell>
        <uv-cell icon="integral-fill" title="退出登录" isLink size="large" :border="false" :cellStyle="cellStyle"
          :clickable="false" @click="onLogout">
          <template #icon>
            <uv-image src="/static/images/my/logout.png" height="24" width="24"></uv-image>
          </template>
        </uv-cell>
      </uv-cell-group>
    </view>
    <uv-modal ref="modal" title="暂未开放" content='请至PC网页端操作'></uv-modal>
  -->
  </view>
</template>
<script setup lang="ts">
import { onLoad, onReady, onShow } from '@dcloudio/uni-app'
import { ref, computed, reactive } from 'vue'
import { useMemberStore } from '@/stores'
import { getMemberProfileAPI } from '@/services/profile'
import { getSystemFunctionConfig, saveSystemFunctionConfig } from '@/services/config'
import { themeColor } from '@/utils/index'
import mqttStatus, {
  cmdKey,
  getAllConfig,
  applicationConfig,
  updateConfig,
  execCmd
} from '@/utils/mqtt';
import dayjs from 'dayjs'


// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

const cellStyle = reactive({
  minHeight: '120rpx',
  backgroundColor: 'white'
})

const modal = ref()

// 获取会员信息
const memberStore = useMemberStore()

const profile = ref({
  id: '',
  name: '',
  nickName: '',
  avatar: '',
  phone: '',
  income: 0,
  levelId: '',
  levelName: '',
  needAuth: true,
  balance: 0,

})

const actionModulesListView = ([
  {
    action: 'order_plan',
    action_name: '计划下单',
  }, {
    action: 'price_fix',
    action_name: '远程定价',
  }, {
    action: 'personnel_management',
    action_name: '人员管理',
  }, {
    action: 'customer_recharge',
    action_name: '客户充值',
  }
])

const actionsListView = reactive([
  {
    action: 'automatic_audit',
    action_name: '自动审核',
    action_dec: '自动审核司机预约数据默认一年',
    icon: '/static/images/my/auto_audit.png',
    action_statu: false,
    loading: false,
    rawValue: { appointEffectiveTimespan: 30 },
    toggle: (val: boolean) => {
      uni.showLoading({
        title: '切换中...',
        mask: true,
      })
      actionsListView[0].loading = true
      saveSystemFunctionConfig({
        enableAppointAutoPass: val,
        appointAutoPassStart: val ? dayjs().format('YYYY-MM-DD') : null,
        appointAutoPassEnd: val ? dayjs().add(1, 'year').format('YYYY-MM-DD') : null,
        appointEffectiveTimespan: actionsListView[0].rawValue?.appointEffectiveTimespan
      }).then(() => {
        actionsListView[0].action_statu = val
        actionsListView[0].loading = false
        uni.showToast({
          title: '操作成功',
          icon: 'none',
          mask: true
        })
      }).catch(() => { }).finally(() => { uni.hideLoading() })
    }
  }, {
    action: 'data_hiding',
    action_name: '数据隐藏',
    action_dec: '开启后软件不显示100吨以上的数据，除非取消',
    icon: '/static/images/my/data_hide.png',
    action_statu: false,
    loading: true,
    toggle: (val: boolean) => {
      actionsListView[1].loading = true
      uni.showLoading({
        title: '切换中...',
        mask: true,
      })
      applicationConfig.systemCfg.weighting.maxAbnormalData = val ? '100000' : ''
      
      updateConfig({
        systemCfg: {
          weighting: applicationConfig.systemCfg.weighting
        }
      }, ({
        Success,
        Message
      }) => {
        actionsListView[1].action_statu = val
        actionsListView[1].loading = false
        uni.showToast({
          title: Success ? '操作成功' : Message,
          icon: 'none',
          mask: true
        })
      })
    }
  }, {
    action: 'gate_control',
    action_name: '道闸控制',
    action_dec: '开启后全部道闸将会一直在起杆状态，除非取消',
    icon: '/static/images/my/gate_control.png',
    action_statu: false,
    loading: false,
    toggle: (val: boolean) => {
      actionsListView[2].loading = true
      execCmd(cmdKey.openAllGate, val ? 'True' : 'False', ({
        Success,
        Message
      }) => {
        actionsListView[2].action_statu = val
        actionsListView[2].loading = false
        uni.showToast({
          title: Success ? '操作成功' : Message,
          icon: 'none',
          mask: true
        })
      })
    }
  }
])

onLoad(() => {
  
})

onShow(() => {
  if (memberStore.profile) {
    getMemberProfileAPI(null).then(data => {
      if (data.activeCodes.length && !memberStore.detailProfile.selectedActiveCode) {
        const code = data.activeCodes[0]
        data.selectedActiveCode = code.hardwareCode
      } else {
        data.selectedActiveCode = memberStore.detailProfile.selectedActiveCode
      }
      memberStore.setDetailProfile(data)
      profile.value = data
    }).catch(() => { })

    getSystemFunctionConfig().then(data => {
      actionsListView[0].rawValue = data
      actionsListView[0].action_statu = data.enableAppointAutoPass
    }).catch(() => { }).finally(() => { })

    if (!mqttStatus.online) {
      uni.showModal({
        title: '提示',
        content: '云服务已离线,请前去主页连接后重试',
      })
      return
    }

    getAllConfigData()
    
  }

})

const getAllConfigData = () => {

  uni.showLoading({
    title: '获取配置中...',
    mask: true
  })

  let appAnswered = false

  setTimeout(() => {
    if (!appAnswered) {
      uni.hideLoading()
      uni.showToast({
        icon: 'none',
        title: '程序响应超时'
      })
    }
  }, 10000)

  
  if (!mqttStatus.online) {
    console.log('offline')
    return
  }
  
  getAllConfig(({
    Success,
    Message,
    Body
  }) => {
    appAnswered = true
    uni.hideLoading()
    if (!Success) {
      uni.showToast({
        title: Message,
        icon: 'none'
      })
      return
    }
    Object.keys(applicationConfig).forEach(k => {
      applicationConfig[k] = Body[k]
    })
    const num = Number(applicationConfig.systemCfg.weighting.maxAbnormalData)
    actionsListView[1].action_statu = !isNaN(num) && num > 0
    actionsListView[1].loading = false

  })
}

const tips = () => {
  modal.value.open()
}


const to = (url: string, checkAuth: boolean) => {
  uni.navigateTo({
    url: checkAuth ? (memberStore.profile ? url : '/pages/login/login') : url
  })
}

const isChecked = ref(false)
const handleSwitchChange = (e, item) => {

  item.toggle(e)


}

// 退出登录
const onLogout = () => {
  // 模态弹窗
  uni.showModal({
    content: '是否退出登录？',
    confirmColor: themeColor,
    success: (res) => {
      if (res.confirm) {
        // 清理用户信息
        memberStore.clearProfile()
        uni.reLaunch({
          url: '/pages/index/index'
        })
      }
    },
  })
}

</script>
<style lang="scss">
.user_content {
  display: flex;
  align-items: center;
  margin: 48px 20px 20px 20px;

  .user_detail_content {
    display: flex;
    flex: 1;
    justify-content: space-between;
    align-items: center;
    margin-left: 10px;

    .user_detail_login_content {
      .user_detail_title {
        font-size: 14px;
      }

      .user_detail_id {
        font-size: 12px;
      }
    }

    .user_detail_login_btn {
      color: white;
      background-color: rgba(26, 102, 255, 1);
      font-size: 12px;
      padding: 10px 20px;
      border-radius: 10px;
    }
  }
}

.action_content {
  font-size: 14px;
  margin: 20px 10px 20px 10px;

  .action_title {
    color: gray;
    margin-left: 10px;
  }

  .action_list_content {
    display: flex;
    background-color: white;
    margin: 10px 5px;
    padding: 10px 0px 10px 10px;
    border-radius: 10px;

    .action_list_icon {
      width: 40px;
      height: 40px;
      border-radius: 10px;
      background-color: #FAFAFA;
    }

    .action_list_detail_content {
      display: flex;
      width: 100%;
      justify-content: space-between;
      align-items: center;
      margin: 0 10px;

      .action_list_detail_content_text {
        .action_list_detail_name {
          font-size: 12px;
        }

        .action_list_detail_dec {
          color: gray;
          font-size: 10px;
          text-overflow: ellipsis;
        }
      }
    }
  }
}

.module_content {
  margin: 20px 10px 20px 10px;

  .module_title {
    color: gray;
    margin-left: 10px;
  }

  .module_item {
    display: flex;
    color: white;

    .module_item_detail {
      display: flex;
      justify-content: center;
      height: 100px;
      width: 100px;
      background-color: #C4C4C4;
      border-radius: 10px;
      margin: 5px 10px;
      overflow-x: auto;
      overflow-y: hidden;
      flex: 0 0 auto;
      text-align: center;
      align-items: center;
    }

  }
}

.action_switch {
  margin-left: 10px;

  .uni-switch-input,
  .uni-switch-input::before,
  {
  height: 22px;
  width: 42px;
}

.uni-switch-input::after {
  width: 20px;
  height: 20px;
}
}

.scroll-view {
  white-space: nowrap;
  overflow: hidden;
}

.item {
  display: inline-block;
  width: 100px;
  height: 100px;
  background-color: #f0f0f0;
  text-align: center;
  line-height: 100px;
  margin-right: 10px;
}
</style>
